import cloud from '@tbmp/mp-cloud-sdk';
cloud.init({
  env: 'test'
});
App({
  cloud,
  onLaunch(options) {
    // console.log('App Launch', options);
    // console.log('getSystemInfoSync', my.getSystemInfoSync());
    // console.log('SDKVersion', my.SDKVersion);
    this.getUser();

  },
  onShow() {
    // console.log('App Show');
  },
  onHide() {
    console.log('App Hide');
  },
  globalData: {
    hasLogin: false,
    user_name: ''
  },

  //返回开始时间和结束时间
  // var times = this.callTime(1,0); (第一个参数‘1’代表往前推，‘2’代表往后推)传0是获取当前时间，传7是获取7天之前的数据，以此类推
  callTime(type, day) {
    var days = day;
    var nowdate = new Date();
    if (day == 0) {
      var time = this.dateFormat(nowdate, "yyyy-MM-dd");
    } else {
      if (type == 2) {
        var olddate = new Date(nowdate.getTime() + days * 24 * 60 * 60 * 1000);// 一个月之后
      } else {
        var olddate = new Date(nowdate.getTime() - days * 24 * 60 * 60 * 1000);// 一个月前
      }
      var time = this.dateFormat(olddate, "yyyy-MM-dd");
    }
    return time
  },
  //获取当前时间解析
  dateFormat(thisDate, fmt) {
    var o = {
      "M+": thisDate.getMonth() + 1,
      "d+": thisDate.getDate(),
      "h+": thisDate.getHours(),
      "m+": thisDate.getMinutes(),
      "s+": thisDate.getSeconds(),
      "q+": Math.floor((thisDate.getMonth() + 3) / 3),
      "S": thisDate.getMilliseconds()
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (thisDate.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  },
  //检测用户有没有登录
  getUser() {
    var that = this;
    my.getStorage({
      key: 'users',
      success: function (res) {
        // console.log(res);
        // console.log(res.data);
        if (res.data) {
          that.globalData.user_name = res.data.user_name;
        } else {
          that.getAuth();
        }
      },
      fail: function (res) {
        that.getAuth();
        my.alert({ content: res.errorMessage });
      }
    });
  },
  //用户授权
  getAuth() {
    var that = this;
    my.authorize({
      scopes: 'scope.userInfo',
      success: (res) => {
        my.getAuthUserInfo({
          success: (userInfo) => {
            my.setStorage({
              key: 'users',
              data: {
                user_name: userInfo.nickName
              },
              success: function () {
                // my.alert({ content: '写入成功' });
                that.onLaunch();
              }
            });
            my.alert({
              content: 'user' + JSON.stringify(userInfo),
            });
          }
        });
      },
    });
  },
  //图片上传
  upimg() {
    // var that = this;
    var imgUrl = '';
    my.qn.chooseFile({
      count: 2,   // 返回的文件数，默认 1
      type: 0x01, // 图片=0x01，文档=0x02，多媒体=0x04，自由组合，默认 0x01
      success: (res) => {
        my.showLoading({ content: '上传中...' });
        // my.alert({ title: res.apFilePaths[0] });
        const { cloud } = getApp();
        var result = cloud.file.uploadFile({
          filePath: res.apFilePaths[0],
          fileType: 'image',
        });
        result.then(function (data) {
          // 提交到后端处理
          my.hideLoading();
          imgUrl = data.url;
          // that.setData({
          //   picUrl:JSON.stringify(data.url)
          // })
          // my.alert({ title: JSON.stringify(data) });
        });
      },
    });
    return imgUrl;
  },
  //视频上传
  upvideo() {
    my.qn.chooseFile({
      count: 1,   // 返回的文件数，默认 1
      type: 0x04, // 图片=0x01，文档=0x02，多媒体=0x04，自由组合，默认 0x01
      success: (res) => {
        //my.alert({ title: res.apFilePaths[0] });
        const { cloud } = getApp();
        my.showLoading({ content: '上传中...' });
        var result = cloud.file.uploadFile({
          filePath: res.apFilePaths[0],
          fileType: 'video',
        });
        result.then(function (data) {
          // 提交到后端处理
          my.hideLoading();
          // my.alert({ title: JSON.stringify(data) });
        });
        //console.log(res); // {"apFilePaths":["https://appres.wiflill.com/publictmp/2737175a-6c44-4ed4-ba84-6675e7e258d9test1.xlsx","https://appres.wiflill.com/publictmp/40d43fa5-1de6-4bce-a287-4471a5a47f97test2.xlsx"],"success":true} 
      },
    });
  },
  //请求封装

  async xdapi(api, data, callback) {
    try {
      const { cloud } = getApp();
      my.showLoading();
      const result = await cloud.application.httpRequest({
        'path': '/shop_reds/public/',
        'method': 'POST',
        'params': { "service": api, "return_format": "taobao",'user_platform_id':1,'platform_id':1,'user_id':3,'user_name':this.globalData.user_name, ...data },
        'body': { "return_format": "taobao" },
        'exts': {"timeout":2000}
      });
      callback(result);
    } catch (e) {
      my.hideLoading();
    }
  },
  //请求回调
  async xdapis(api, data, callback) {
    try {
      const { cloud } = getApp();
      my.showLoading();
      const result = await cloud.application.httpRequest({
        'path': '/shop_reds/public/',
        'method': 'POST',
        'params': { "service": api, "return_format": "taobao", 'user_platform_id': 1, 'platform_id': 1, 'user_id': 3, 'user_name': this.globalData.user_name, ...data },
        'body': { "return_format": "taobao" },
        'exts': { "timeout": 10000 }
      });
      callback(result);
    } catch (e) {
      my.hideLoading();
      my.alert({
        title: '提示',
        content: '系统错误:' + e.message
      });
    }
  },
  //请求回调
  async xdapiTop(api, data, callback) {
    try {
      const { cloud } = getApp();
      my.showLoading();
      const result = await cloud.topApi.invoke({
        api: api,
        data: data
      });
      callback(result);
    } catch (e) {
      my.hideLoading();
      my.alert({
        title: '提示',
        content: '系统错误:' + e.message
      });
    }
  },
  //显示加载中
  show() {
    my.showLoading({
      content: '加载中...'
      // delay: '0',
    });
    setTimeout(() => {
      my.hideLoading();
    }, 5000);
  },
  //隐藏加载中
  hide() {
    my.hideLoading();
  },
});
